package com.itfreer.arcgis.utils;

import com.esri.arcgisruntime.data.Field;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class DbValueConvertUtils {

    /**
     * @Title: ConvertValue @Description: 转换数据值 @param @param fm @param @param
     * fieldName @param @param obj @param @return @return Object 返回类型 @throws
     */
    public static Object ConvertValue(Field.Type fm, Object obj) {
        if (null == obj || "".equals(obj)) {
            return null;
        }

        String strObj = obj.toString();
        if ("null".equals(strObj)) {
            return null;
        }
        Object value = null;
        switch (fm) {
            case TEXT:
            case GUID:
            case OID:
            case GLOBALID:
                value = strObj;
                break;
            case DATE:
                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if ("null".equals(strObj))
                        return null;
                    strObj = strObj.replace(" 00:00:00", "");
                    strObj = strObj.replace("/", "-");
                    // 处理如果类型为2013-12没有日期的类型 : 陈旭 2013.12.24
                    String[] strObjs = strObj.split("-");
                    if (strObjs.length == 2) {
                        strObj = strObj + "-01";
                    }
                    value = dateFormat.parse(strObj);
                } catch (Exception e1) {
                    value = null;
                }
                break;
            case FLOAT:
            case DOUBLE:
                if (obj instanceof Double)
                    value = obj;
                else {
                    strObj = getDigitValue(strObj);
                    Double de = 0d;
                    try {
                        de = Double.parseDouble(strObj);
                        value = de;
                    } catch (Exception e) {
                    }
                }
                break;
            case SHORT:
            case INTEGER:
                if (obj instanceof Integer)
                    value = obj;
                else {
                    strObj = getDigitValue(strObj);
                    try {
                        value = Integer.parseInt(strObj);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case BLOB:
                value = obj;
                break;
            case UNKNOWN:
            case GEOMETRY:
            case RASTER:
            case XML:
                break;
            default:
                break;
        }
        return value;
    }

    static String getDigitValue(String strObj) {
        if (strObj.toUpperCase() == "TRUE" || strObj == "是")
            return "1";
        else if (strObj.toUpperCase() == "FALSE" || strObj == "否")
            return "0";
        else
            return strObj;
    }
}
